package com.roy.ESClient;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class ESClientMain {

	private static HttpHost[] esHosts = new HttpHost[] { new HttpHost("172.16.48.53", 9200) };
	private static long totalHits;

	public static void main(String[] args) {
		 // 1.创建RestClient对象
		RestClientBuilder restClient = RestClient.builder(esHosts);
		RestHighLevelClient client = new RestHighLevelClient(restClient);
        // 2.创建BoolQueryBuilder对象
		BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 3.设置boolQueryBuilder条件
		BoolQueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("@timestamp").gte(Long.parseLong("1587074002000")).format("epoch_millis"));
        BoolQueryBuilder appBoolQuery = QueryBuilders.boolQuery().minimumShouldMatch(1);
        // 2020/02/12 针对风控返回信息码为空的情况做日志过滤
        builder.filter(QueryBuilders.boolQuery().mustNot(QueryBuilders.queryStringQuery("RFK_TXN_SND_*").field("log_txCode")));
        
        // 聚合size=100 用来解决Elasticsearch在分组聚合精度不准确的问题
        
        TermsAggregationBuilder tb1 = AggregationBuilders.terms("topAgg").field("log_txCode").size(100).order(BucketOrder.aggregation("topCountAgg", true));
        ValueCountAggregationBuilder stb2 = AggregationBuilders.count("topCountAgg").field("log_requestId");
        AvgAggregationBuilder stb1 = AggregationBuilders.avg("topAvgAgg").field("log_txDuration");
        
        tb1.subAggregation(stb2).subAggregation(stb1);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(builder)
                .aggregation(tb1);
//        searchSourceBuilder.sort("topAgg", SortOrder.DESC);
        // 获取的字段（列）和不需要获取的列
//        searchSourceBuilder.fetchSource(new String[]{"log_txCode", "source"}, new String[]{});
        // 设置排序规则
//        searchSourceBuilder.sort("postdate", SortOrder.ASC);
        // 设置超时时间为2s
        searchSourceBuilder.timeout(new TimeValue(2000));
        
//        searchSourceBuilder.aggregation(AggregationBuilders.dateHistogram(name))
 
        // 2.创建并设置SearchRequest对象
        SearchRequest searchRequest = new SearchRequest();
        // 设置request要搜索的索引和类型
        searchRequest.indices("log-*-txnplte-*").types("doc");
        // 设置SearchSourceBuilder查询属性
        searchRequest.source(searchSourceBuilder);
        
        
        // 3.查询
        try {
			SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
			totalHits = searchResponse.getHits().totalHits;
			SearchHits hits = searchResponse.getHits();
			Terms topagg = searchResponse.getAggregations().get("topAgg");
			
			List<? extends Terms.Bucket> buckets = topagg.getBuckets();
			
			for(int i = 0 ; i < 20 ; i ++) {
				Terms.Bucket bucket = buckets.get(i);
				Object key = bucket.getKey();
				long docCount = bucket.getDocCount();
				ValueCount countAgg = bucket.getAggregations().get("topCountAgg");
				
				
				Avg subagg = bucket.getAggregations().get("topAvgAgg");
				
				System.out.println("key:"+key+";docCount:"+docCount+";countAgg:"+countAgg.getValue()+";topAvgAgg:"+subagg.getValue());
			}
//			for(SearchHit hit:hits) {
//				System.out.println(hit.getSourceAsString());
//			}
			System.out.println(totalHits);
			client.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			System.exit(-1);
		}

	}
}
